
import maya.cmds as cmds
import AntsCrowd.transform as transform
import AntsCrowd.Terrain as Terrain
import glob
import time
import random
import math

from maya.OpenMaya import *
import AntsCrowd.ProximityDataBase as PD
import AntsCrowd.Worker as Worker

reload(transform)
reload(Terrain)
reload(PD)
reload(Worker)

instance_mode = 1
cube_mode = 1
terrain_mode = 1

workerList = []

def createPD():
    _center = MVector( 0.0, 0.0, 0.0 )
    _divisions = MVector( 50.0, 1.0, 50.0 )
    _dimensions = MVector( 200.0, 200.0, 200.0 )
    return PD.LQProximityDataBase( _center, _dimensions, _divisions )
    
def createWorker( _count ):
    _pd = createPD()
    for _idx in xrange( _count ):
        _worker = Worker.Worker( _pd )
        workerList.append( _worker )

def runProc(grd = 100 , ants = 10 , _MaxTime = 240):
    cmds.file( f=True, new=True )
    
    if cube_mode == 0 :
        cmds.file( mf = False)
        cmds.file( f=True, new=True )        
    else :
        _Filename = cmds.fileDialog(m = 0)
        if _Filename == '' : 
            _Filename = glob.glob( r"X:\Works\3d\ant\model\Ants_female56_*.mb" )[-1]
        cmds.file( mf = False )
        cmds.file( _Filename, o = 1 )
    
    try :
        cmds.timer( s=True ,lap=1,name= 'tester' )
    except :
        cmds.timer( e=True ,name= 'tester')
        cmds.timer( s=True ,lap=1,name= 'tester' )
    print '\n\nProcess start\n',time.ctime(), '\n\n'
    
    _Terrain = Terrain.Terrain( r"\\192.168.131.222\kali\Project\AntsCrowd\Resource\heightmap.jpg" , grd )
    
    if cube_mode == 1 :
        _ModelList = _Terrain.fnCreateModel( 'ant_all', ants )
    elif cube_mode == 0 :
        _ModelList = _Terrain.fnCreateNull( ants )
    else :
        _ModelList = _Terrain.fnCreateCube( ants )
    
    _ObstacleList = _Terrain.fnCreateObstacle( 0 )
    
    createWorker( ants )
    
    print 'CreateModel'    
    
    cmds.playbackOptions( maxTime = _MaxTime )
    cmds.playbackOptions( minTime = 0 )
    
    for _Idx in xrange(len(_ModelList)) :
        _ModelX = 0
        _ModelY = 0
        
        if instance_mode:
            #instance
            _ModelX = cmds.getAttr( _ModelList[_Idx][0] + '.translateX' )
            _ModelY = cmds.getAttr( _ModelList[_Idx][0] + '.translateZ' )
            
        else :            
            # duplicate
            _ModelX = cmds.getAttr( _ModelList[_Idx]['main'][0] + '.translateX' )
            _ModelY = cmds.getAttr( _ModelList[_Idx]['main'][0] + '.translateZ' )
            
        workerList[_Idx].position = MVector( _ModelX, 0, _ModelY )
                        
    print 'AddAgent'
     
    for _Idx in xrange( len( _ObstacleList )):
        _ObstacleX = cmds.getAttr( _ObstacleList[_Idx][0] + '.translateX' )
        _ObstacleY = cmds.getAttr( _ObstacleList[_Idx][0] + '.translateZ' )
        _Radius = cmds.getAttr( _ObstacleList[_Idx][1] + '.width' )/2 

    for _TimeCnt in xrange( _MaxTime + 1 ):        
        for _Idx in xrange( len(workerList) ):
            workerList[_Idx].update( 0.0, 1.0 / 24.0 )
            
            _PosX = workerList[_Idx].position.x
            _PosZ = workerList[_Idx].position.z
            _Angle = math.degrees( 0 )
            _Head = FCVector.vector2D( workerList[_Idx].forward.x, workerList[_Idx].forward.z )
            #_Head = _Simulator.mAgentList[_Idx].mHeading
            _info = []
            if terrain_mode:	
                _info = _Terrain.fnGetXZRotateAndHeight(_PosX,1000,_PosZ,_Head)    
                _RotX = transform.RadianToDegree(_info[0])  
                _RotY = transform.RadianToDegree(_info[1])          
                _RotZ = transform.RadianToDegree(_info[2]) 
 
            
            if instance_mode :
                # instance
                if terrain_mode : 
                    cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'rotateX', value = _RotX, t = _TimeCnt ) 
                    cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'rotateZ', value = _RotZ, t = _TimeCnt ) 
                    cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'translateY', value = _info[3], t = _TimeCnt )            
                    cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'rotateY', value = _Angle, t = _TimeCnt )
                else:
                    cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'rotateY', value = _Angle, t = _TimeCnt ) 
                cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'translateX', value = _PosX, t = _TimeCnt )
                cmds.setKeyframe( _ModelList[_Idx][0], attribute = 'translateZ', value = _PosZ, t = _TimeCnt )
               
                
                    
                    
            else :
                #duplicate
                AutoWalk.antwalk( _ModelList[_Idx] )
                
                cmds.setKeyframe( _ModelList[_Idx]['main'][0], attribute = 'translateX', value = _PosX, t = _TimeCnt )
                cmds.setKeyframe( _ModelList[_Idx]['main'][0], attribute = 'translateZ', value = _PosZ, t = _TimeCnt )
                cmds.setKeyframe( _ModelList[_Idx]['main'][0], attribute = 'rotateY', value = _Angle, t = _TimeCnt )
                if terrain_mode : 
                    cmds.setKeyframe( _ModelList[_Idx]['main'][0], attribute = 'translateY', value = _Terrain.fnGetHeight(50,_PosX,_PosZ), t = _TimeCnt )                    
                
                map( lambda n : cmds.setKeyframe( _ModelList[_Idx]['legs'][n], attribute = 'translateY', t = _TimeCnt ) , range(6) )
                map( lambda n : cmds.setKeyframe( _ModelList[_Idx]['legs'][n], attribute = 'translateX', value = _PosX, t = _TimeCnt ) , range(6) )
                map( lambda n : cmds.setKeyframe( _ModelList[_Idx]['legs'][n], attribute = 'translateZ', value = _PosZ, t = _TimeCnt ) , range(6) )
                map( lambda n : cmds.setKeyframe( _ModelList[_Idx]['legs'][n], attribute = 'rotateY', value = _Angle, t = _TimeCnt ) , range(6) )
                
            
        print str(_TimeCnt) + ' Frame';
    
    processtime = cmds.timer( e=True ,name= 'tester')    
    print "Process Completed: " , processtime / 60 , 'min'
    
    ## set MAYA up
    cmds.setAttr( "perspShape.farClipPlane" , 1000000 )
    cmds.workspace( cr =  r'X:\Works\3d\ant\antProject' )
    cmds.workspace( r'X:\Works\3d\ant\antProject' , o = 1 )
    #cmds.viewFit()
    
    filelist = glob.glob(r'X:\Works\3d\ant\antProject\scenes\*.m*')
    sceneVer = '01' if filelist == [] else filelist[-1].split('_')[-1].split('.')[0]
    cmds.file( rename='antCrowd_'+str( ants ) + '_' + sceneVer + '.ma' )
    #cmds.delete('pPlane1')
    
if __name__ == "__main__" :
    runProc()   